package com.cochain.ftp;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Component
@Slf4j
public class FtpPoolServiceImpl implements FtpPoolService {


    private MultiFtpClientPoolFun<FtpClientPool> multiFtpClientPoolFun;
    /**
     * 初始化pool
     */
    @PostConstruct
    private void initPool() {
        FtpProperties ftpProperties = FtpProperties.getFtpPropertiesA();
        // (2)构造FtpClientFactory对象
        FtpClientFactory ftpClientFactory = new FtpClientFactory(ftpProperties);
        // (3)构造池对象
        String flag = ftpProperties.getHost() + ":"+ ftpProperties.getPort();
        FtpClientPool ftpClientPool = new FtpClientPool(ftpClientFactory,flag);

        // 如果只是单池的话 ftpClientPool可以直接用了
        // FTPClient ftpClient = ftpClientPool.borrowObject(); // 池获取连接
        // ftpClientPool.returnObject(ftpClient); // 用完还连接

        // (4)多ftp连接池构造
        multiFtpClientPoolFun = new DefaultMultiFtpClientPool();
        multiFtpClientPoolFun.initPool(flag,ftpClientPool);
    }

    /**
     * 获取ftpClient
     */
    @Override
    public FTPClient borrowObject(String flag) {
        if (this.multiFtpClientPoolFun != null) {
            try {
                FtpClientPool ftpClientPool = this.multiFtpClientPoolFun.getPool(flag);
                return ftpClientPool.borrowObject();
            } catch (Exception e) {
                log.error("获取 FTPClient 失败 ", e);
            }
        }
        return null;
    }

    /**
     * 归还 ftpClient
     */
    @Override
    public void returnObject(FTPClient ftpClient,String flag) {
        FtpClientPool pool = multiFtpClientPoolFun.getPool(flag);
        if (pool != null && ftpClient != null) {
            pool.returnObject(ftpClient);
        }
    }
}

